package com.samuel.algorithm.sort;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 冒泡排序
 * k1 < k2
 * 每一轮冒泡都把最大的值排到最后，待排序长度减一，然后循环
 */
public class BubbleSort {


    public static void main(String[] args) {
        int[] nums = {6, 3, 5, 2, 4, 9, 18, 7};
        printArrays(nums);
        System.out.println("---");
        bubble(nums);
        System.out.println("---");
        printArrays(nums);
        int[] numsPlus = {6, 3, 5, 2, 4, 9, 18, 7};
        //352469718
        bubblePlus(numsPlus);

    }


    private static void bubble(int[] nums) {
        if (null == nums || nums.length <= 1) {
            return;
        }
        int toSortLength = nums.length - 1;
        while (toSortLength > 1) {
            for (int i = 0; i < toSortLength; i++) {
                if (nums[i] > nums[i + 1]) {
                    int temp = nums[i];
                    nums[i] = nums[i + 1];
                    nums[i + 1] = temp;
                }
            }
            toSortLength--;
            printArrays(nums);
        }
    }

    private static void bubblePlus(int[] nums) {
        if (null == nums || nums.length <= 1) {
            return;
        }
        int rightMaxIndex = nums.length - 1;
        do {
            int lastBubbleIndex = 0;
            for (int i = 0; i < rightMaxIndex; i++) {
                if (nums[i] > nums[i + 1]) {
                    int temp = nums[i];
                    nums[i] = nums[i + 1];
                    nums[i + 1] = temp;
                    lastBubbleIndex = i;
                }
            }
            rightMaxIndex = lastBubbleIndex;
            printArrays(nums);
        } while (rightMaxIndex != 0);
    }

    private static void printArrays(int[] nums) {
        String collect = Arrays.stream(nums)
                .mapToObj(Integer::toString)
                .collect(Collectors.joining("\t"));
        System.out.println(collect);
    }
}
